<?php

namespace mpend\modules\share\models;

use Yii;
use yii\db\Exception;
use common\logics\WorkbookLogic;
use common\models\work\WorkCategory;
use common\models\workbook\WorkbookMember;
use common\models\workbook\WorkbookInvite;
use common\models\workbook\WorkbookInviteLog;
use common\helpers\Url;

/**
 * 方案基础模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class WorkerJoinForm extends \common\base\FormModel {

    /**
     * @var string 姓名
     */
    public $user_id;

    /**
     * @var string 姓名
     */
    public $realname;

    /**
     * @var string 电话
     */
    public $mobile;

    /**
     * @var integer 工种
     */
    public $category_id;

    /**
     * @var string 日薪
     */
    public $wage;

    /**
     * @var string 日薪
     */
    public $type;

    /**
     * @var integer 记工簿
     */
    public $workbook_id;

    /**
     * @var string 数据原型模型
     */
    protected $modelClass = WorkbookInvite::class;

    /**
     * @var WorkbookLogic|null 
     */
    private $_workbook = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['realname', 'category_id', 'wage'], 'required'],
            [['workbook_id', 'user_id', 'category_id'], 'integer'],
            [['realname'], 'string', 'max' => 30],
            [['wage'], 'number'],
            [['mobile'], 'string', 'max' => 11],
            [['type'], 'string', 'max' => 20],
            [['realname'], '\common\validators\WordFilterValidator'],
            ['id', 'validateModel'],
            ['user_id', 'validateUser'],
        ];
    }

    /**
     * 验证记工本状态
     * @param string $attribute 
     */
    public function validateModel($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $invite = $this->getModel();
        if (!$invite || $invite->isNewRecord) {
            return $this->addError($attribute, '邀请内容不存在');
        }
        if (!$invite->getIsActive()) {
            return $this->addError($attribute, '邀请链接已失效或已过期');
        }
        $this->_workbook = $invite->workbook;
    }

    /**
     * 验证记工本状态
     * @param string $attribute 
     */
    public function validateUser($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $invite = $this->getModel();
        if ($invite->user_id === $this->user_id) {
            return $this->addError($attribute, '您已加入了当前记工薄');
        }
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'content' => '内容',
            'user_id' => '用户',
            'images' => '图片',
            'attachs' => '文件',
        ];
    }

    /**
     * @return WorkbookLogic
     */
    public function getWorkbook() {
        return $this->_workbook;
    }

    public function setExtraAttributes($model) {
        
    }

    public function dumpJoinSuccess() {
        $invite = $this->getModel();
        $message = '您已成功加入该记工薄，点击下方按钮即可进入记工薄开始记工';
        $confirmText = '进入记工';
        if ($invite->type == WorkbookInvite::TYPE_MANAGE) {
            $mplink = Url::to(['/pages/teambook/management/main', 'id' => $invite->workbook_id]);
        } else {
            $mplink = Url::to(['/pages/teambook/intrant/main', 'id' => $invite->workbook_id]);
        }
        return [
            'mplink' => $mplink,
            'message' => $message,
            'confirmText' => $confirmText,
        ];
    }

    public function save() {
        if (!$this->validate()) {
            return $this->dumpError();
        }
        /* @var $invite WorkbookInvite */
        $invite = $this->getModel();
        $category = WorkCategory::findOne($this->category_id);

        if ($invite->member) {
            $member = $invite->member;
            $member->user_id = $this->user_id;
        } else {
            $member = WorkbookMember::findOrNew([
                'workbook_id' => $invite->workbook_id,
                'user_id' => $this->user_id,
            ]);
            if ($member->isNewRecord) {
                $member->setAttributes([
                    'from_user_id' => $invite->user_id,
                    'status' => WorkbookMember::STATUS_ACTIVE,
                ]);
            }
        }
        $roleId = 0;
        if ($invite->type == WorkbookInvite::TYPE_MANAGE) {
            $roleId = WorkbookMember::ROLE_ADMIN;
        }

        $member->setAttributes([
            'role_id' => $roleId,
            'category_id' => $this->category_id,
            'profession' => $category ? $category->name : '',
            'realname' => $this->realname,
            'mobile' => $this->mobile,
            'wage' => (float) $this->wage,
        ]);

        $inviteLog = WorkbookInviteLog::findOrNew([
            'invite_id' => $invite->id,
            'user_id' => $this->user_id,
            'status' => WorkbookInviteLog::STATUS_ACTIVE,
            'deleted_at' => 0,
        ]);
        $inviteLog->setAttributes([
            'workbook_id' => $invite->workbook_id,
            'from_user_id' => $invite->user_id,
            'type' => $invite->type,
            'description' => '描述',
            'joined_at' => time(),
            'status' => WorkbookInviteLog::STATUS_ACTIVE,
        ]);

        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$member->save()) {
                return $this->dumpError('工人信息保存失败');
            }
            $inviteLog->member_id = $member->id;
            if (!$inviteLog->save()) {
                return $this->dumpError('工人信息保存失败');
            }
            if ($invite->member_id) {
                $invite->status = WorkbookInvite::STATUS_COMPLETE;
                if (!$invite->save()) {
                    return $this->dumpError('工人信息保存失败');
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
        }
        return $this->dumpJoinSuccess();
    }

}
